import '../../public.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  String? userName;
  String? password;
  bool _isObscure = true;
  bool _isLoading = false;

  void login(UserModel userModel, BuildContext context) async {
    final loginForm = formKey.currentState;
    if (loginForm!.validate()) {
      loginForm.save();
      setState(() {
        _isLoading = true;
      });
      try {
        final resp = await AuthApi.login(
          LoginDto(
            systemCode: 1,
            userName: userName!,
            password: password!,
            from: Platform.isAndroid ? 1 : 2,
          ),
        );
        StorageManager.ls.setItem('token', resp.content!.token!);
        await userModel.init();
        RouterHelper.navigator.pushReplacementNamed(Routers.main);
      } catch (e) {
        Toast.show('Login failed: $e');
      } finally {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final userModel = Provider.of<UserModel>(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        children: [
          wellCome(context),
          Form(
            key: formKey,
            child: Column(
              children: [
                accountItem(context),
                passwordItem(context),
                const SizedBox(height: 16),
                Align(
                  alignment: Alignment.centerRight,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 30),
                    child: TextButton(
                      onPressed: () {
                        RouterHelper.navigator.pushNamed(Routers.resetPassword);
                      },
                      child: const Text(
                        'Forgot Password?',
                        style: TextStyle(color: Colors.blue, fontSize: 14),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 15,
                    vertical: 30,
                  ),
                  child: Align(
                    alignment: Alignment.center,
                    child: RichText(
                      text: TextSpan(
                        children: [
                          TextSpan(
                            text: "Not registered yet? ",
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[600],
                            ),
                          ),
                          TextSpan(
                            text: "Sign up",
                            style: const TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              fontSize: 14,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                RouterHelper.navigator.pushNamed(
                                  Routers.regist,
                                );
                              },
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextButton(
                    onPressed: _isLoading
                        ? null
                        : () => login(userModel, context),
                    style: ButtonStyle(
                      shape: WidgetStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      backgroundColor: WidgetStateProperty.all(Colors.black),
                      minimumSize: WidgetStateProperty.all(
                        const Size(double.infinity, 50),
                      ),
                    ),
                    child: _isLoading
                        ? const SizedBox(
                            height: 24,
                            width: 24,
                            child: CircularProgressIndicator(
                              color: Colors.white,
                              strokeWidth: 2,
                            ),
                          )
                        : const Text(
                            'SIGN IN',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget wellCome(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 30),
          Text(
            'Sign in',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            'Welcome back! Fill in your details to access your account',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget accountItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        onSaved: (value) => userName = value,
        onChanged: (value) => userName = value,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter your account name';
          }
          return null;
        },
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter your account name",
          labelText: "Account Name",
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  Widget passwordItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        obscureText: _isObscure,
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter your password';
          }
          return null;
        },
        onSaved: (value) => password = value,
        onChanged: (value) => password = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Please enter your password",
          labelText: "Password",
          suffixIcon: IconButton(
            icon: Icon(
              _isObscure ? Icons.visibility : Icons.visibility_off,
              color: Colors.grey[500],
            ),
            onPressed: () {
              setState(() {
                _isObscure = !_isObscure;
              });
            },
          ),
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }
}
